<template>
  <div
    :class="{'pdr': isPreView && element.type === 'richEditor', 'mobile-element-item': showMobilePage, 'normal-element-item': !showMobilePage, 'flexStart': isDetail && element.type ==='textarea'}"
    :style="getStyle(element)"
    class="element-item">
    <template v-if="!isDetail && (!element.options.readonly)">
      <template v-if="element.type === 'input' || element.type === 'textarea'">
        <el-input
          v-if="!hasContentCache(element) && (element.type === 'textarea' || !element.options.defaultType)"
          :ref="`input_${element.key}`"
          v-model="computedValue"
          :style="widthStyle"
          :rows="!element.options.isResponsive?element.options.rows || 3:1"
          :placeholder="element.options.placeholder"
          :disabled="element.options.disabled && !isInDetail"
          :maxlength="element.options.maxlength"
          :type="element.type === 'textarea'?'textarea':element.options.dataType"
          :autosize="element.type === 'textarea' && element.options.isResponsive?{ minRows: 1, maxRows: element.options.rows || 3 }:false"
          :class="{'input-percentage': element.options.isShowPercentage}"
          class="defaultWidth"
          resize="none"
          size="small"
          @focus="getFocus"
          @input="changeInput($event, element)"
          @change="numberInputChange(element)"
        >
          <div v-if="element.options.isShowPercentage" slot="append" class="autocomplete-append input-percentage-append">%</div>
        </el-input>
        <el-autocomplete
          v-else
          v-model="computedValue"
          :fetch-suggestions="suggestionsSearch"
          :style="widthStyle"
          :placeholder="element.options.placeholder"
          :disabled="element.options.disabled && !isInDetail"
          :maxlength="Number(element.options.maxlength)"
          :type="element.options.dataType"
          :readonly="!element.options.defaultType ? !element.options.contentCache : !element.options.isCanEdit"
          :class="{'input-percentage': element.options.isShowPercentage, 'auto-input': isTable}"
          value-key="id"
          size="small"
          class="defaultWidth"
          @select="handleAutocompleteSelect"
          @change="numberInputChange(element)"
        >
          <div v-if="element.options.isShowPercentage" slot="suffix" class="autocomplete-append input-percentage-append">%</div>
          <div v-if="element.options.isShowPercentage || (!element.options.defaultType && element.options.contentCache) ? false : !element.options.isCanEdit" slot="append" class="autocomplete-append">
            <div v-if="!element.options.isCanEdit" class="el-icon-circle-close clear-autocomplete" @click="clearInputValue(element)"/>
          </div>
        </el-autocomplete>
      </template>
      <LinkOptions
        v-else-if="element.type === 'link'"
        :style="getStyle(element)"
        v-model="computedValue"
        :element="element"
        :is-weibo-or-weixin="isWeiboOrWeixin"
        :is-table="isTable"
        :width-style="widthStyle"
        @input="changeInput($event, element)"
        @change="numberInputChange(element)"
      />
      <template v-else-if="element.type === 'select'">
        <el-select
          v-if="!selectFlag"
          v-model="computedValue"
          :disabled="element.options.disabled && !isInDetail"
          :multiple="element.options.multiple"
          :placeholder="element.options.placeholder"
          :style="widthStyle"
          :filterable="true"
          clearable
          value-key="id"
          size="small"
          class="defaultWidth"
          @change="handelChangeValue()"
        >
          <el-option v-for="item in element.options.options" :title="item.id" :key="item.id" :value="item.id" :label="item.id" />
        </el-select>
      </template>
      <template v-else-if="element.type == 'radio'">
        <el-radio-group v-model="computedValue" :disabled="element.options.disabled && !isInDetail" class="ellipsisOne-group" @change="handelChangeValue()">
          <el-radio v-for="item in element.options.options" :key="item.id" :label="item.id">
            <div class="font-14 ellipsisOne">{{ item.id }}</div>
          </el-radio>
        </el-radio-group>
      </template>
      <template v-else-if="element.type == 'checkbox'">
        <el-checkbox-group v-model="computedValue" :disabled="element.options.disabled && !isInDetail" class="ellipsisOne-group" @change="handelChangeValue()">
          <el-checkbox v-for="item in element.options.options" :key="item.id" :label="item.id">
            <div class="font-14 ellipsisOne">{{ item.id }}</div>
          </el-checkbox>
        </el-checkbox-group>
      </template>
      <el-date-picker
        v-else-if="element.type == 'date'"
        v-model="computedValue"
        :type="getType(element)"
        :placeholder="element.options.placeholder"
        :disabled="element.options.disabled && !isInDetail"
        :editable="false"
        :clearable="true"
        :format="element.options.format"
        size="small"
        value-format="timestamp"
        class="defaultWidth"
        @change="handelChangeValue()"
      />
      <template v-else-if="element.type === 'switch'">
        <el-switch v-model="computedValue" :disabled="element.options.disabled && !isInDetail" @change="handelChangeValue()" />
      </template>
      <div
        v-else-if="element.type === 'upAttachment'"
        :class="{'multiple-attachment-container': isTable, 'attachment-container': showMobilePage}"
      >
        <upAttachment
          :is-disabled="element.options.disabled && !isInDetail"
          v-model="computedValue"
          :table-upload="isTable"
          :import-api="isWeiboOrWeixin?'common/file/upload_v2':''"
          :upload-type="isWeiboOrWeixin?0:1"
          :limit-file-size="element.options.limitFileSize || 50"
          :use-inner-upload="isWeiboOrWeixin && useInnerUpload"
          use-origin-name
          class="defaultWidth"
          is-img-show-mode
          @complateSetData="complateSetData(element, $event)"
          @removeFileList="removeFileList(element, $event)">
          <div v-if="isTable" class="upload-btn">
            <span class="content">拖拽文件或</span>
            <span class="content-link">点击上传</span>
            <img :src="uploadIcon" alt="">
          </div>
        </upAttachment>
      </div>
      <PostSelect
        v-else-if="element.type === 'post'"
        :is-in-detail="isInDetail"
        v-model="computedValue"
        :element="element"
        :style="widthStyle"
        :is-pre-view="isPreView"
        class="defaultWidth"
        @clearValidate="clearValidate"
        @changeValue="handelChangeValue()" />
      <div v-else-if="element.type === 'address'" class="defaultWidth">
        <three-level-area
          :disabled="element.options.disabled && !isInDetail"
          :select-type="element.options.addressType || 'region'"
          :placeholder="element.options.placeholder"
          :selected-options="computedValue"
          :width-style="widthStyle"
          clearable
          separator="-"
          cascader-size="small"
          @update:options="threeLevelArea($event)" />
      </div>
      <div v-else-if="element.type === 'workflowId'">
        <ToolTip v-if="computedValue" :content="computedValue" />
        <div v-else>--</div>
      </div>
      <DeptSelect v-else-if="element.type === 'department'" :style="widthStyle" :is-in-detail="isInDetail" v-model="computedValue" :is-pre-view="isPreView" :element="element" @changeValue="handelChangeValue()" />
      <UserSelect
        v-else-if="element.type === 'user'"
        :is-in-detail="isInDetail"
        v-model="computedValue"
        :form-options="formOptions"
        :element="element"
        :event-data="eventData"
        :style="widthStyle"
        :is-pre-view="isPreView"
        :subform-index="subformIndex"
        :subform-element="subformElement"
        :class="showMobilePage? '' : 'dynamic-width'"
        @clearValidate="clearValidate"
        @handelChangeValue="handelChangeValue()"
        @changeValue="handelChangeValue()"
        @handleFormUserSelect="handleFormUserSelect"
        @userChange="userChange" />
      <FormulaInput v-else-if="element.type === 'formulaInput'" v-model="computedValue" :element="element" :is-pre-view="isPreView" :style="widthStyle" class="dynamic-width" />
      <template v-else-if="element.type === 'createTime'">
        <div v-if="computedValue">{{ computedValue | format(getFormat(element.options.format)) }}</div>
        <div v-else>--</div>
      </template>
      <template v-else-if="element.type === 'createUser'">
        <CheckUserInfo v-if="getUserName(computedValue)" :label="getUserName(computedValue).userName" :user-id="getUserName(computedValue).id" />
        <div v-else>--</div>
      </template>
      <RichEditor
        v-else-if="element.type === 'richEditor'"
        ref="textEditor"
        :element="element"
        :is-in-detail="isInDetail"
        :import-api="isWeiboOrWeixin?'/common/file/upload_v2':''"
        :is-middle="isMiddle"
        :is-detail="isDetail"
        v-model="computedValue"
        class="richeditor"
        @change="handelChangeValue" />
    </template>
    <template v-else>
      <div v-if="element.options && element.options.isSecret && !element._isShowSecret" class="secret-item">
        <div class="secret-val">******</div>
        <div class="button-text" @click="showSecretModel()">查看</div>
      </div>
      <ToolTip v-else-if="normalType || normalType === 0" :style="{ width: ['input', 'textarea'].includes(element.type) && element.options.width + 'px' }" :content="normalType" />
      <template v-else-if="element.type === 'user' && computedValue">
        <CheckUserInfo v-if="element.options.multiple && computedValue.length" :user-list="computedValue" multiple />
        <CheckUserInfo v-else-if="!element.options.multiple && computedValue" :user-id="computedValue.id" :label="computedValue.userName" />
        <div v-else>--</div>
      </template>
      <template v-else-if="element.type === 'createUser'">
        <CheckUserInfo v-if="getUserName(computedValue)" :label="getUserName(computedValue).userName" :user-id="getUserName(computedValue).id" />
        <div v-else>--</div>
      </template>
      <div v-else-if="element.type ==='textarea'" :title="computedValue" class="textarea-content">{{ trimString(computedValue) }}</div>
      <ToolTip v-else-if="(element.type === 'date' || element.type === 'createTime') && computedValue" :content="computedValue | format(getFormat(element.options.format))" />
      <div v-else-if="element.type === 'switch'">{{ computedValue?'是':'否' }}</div>
      <!-- 换成ImgShowDialog -->
      <!-- <FileShowList v-else-if="element.type === 'upAttachment' && computedValue && computedValue.length" :file-list="computedValue" is-show-single-file /> -->
      <!-- <ImgShowDialog
        v-else-if="element.type === 'upAttachment' && computedValue && computedValue.length"
        :is-edit="false"
        :file-list="computedValue" /> -->
      <!-- 替换成CardThumbnailFiles  -->
      <div v-else-if="element.type === 'upAttachment' && computedValue && computedValue.length" class="donwload-container">
        <CardThumbnailFiles
          :file-list="computedValue"
          style="width: 240px;"/>
        <div v-if="element.options.isAllDownload" class="all-download">
          <el-button :loading="element._downloadLoading" type="primary" size="small" @click="allDownload(computedValue, element)">一键下载</el-button>
        </div>
      </div>
      <ToolTip v-else-if="element.type === 'workflowId' && computedValue" :content="computedValue" />
      <div v-else-if="element.type === 'richEditor'" class="richeditor-readonly" v-html="computedValue === '<p><br></p>' ? '--' : computedValue" />
      <template v-else-if="element.type === 'link'">
        <LinkElement
          v-if="computedValue"
          :element="element"
          :is-table="isTable"
          :link="computedValue"
          :is-in-detail="isInDetail"
          :auto-pick="element.options.autoPick"
          :link-name="element.options.defaultLinkName || '点击查看'" />
        <div v-else>--</div>
      </template>
      <div v-else>--</div>
    </template>
  </div>
</template>

<script>
/**
 * 所有字段展示和修改
 * 新增字段时，记得增加 handelChangeValue 事件
 */
import upAttachment from '@/components/Common/upAttachment/index';
import ImgShowDialog from '@/components/Common/upAttachment/imgShowDialog';
import FileShowList from '@/components/CreateOrder/fileShowList';
import CardThumbnailFiles from '@/components/Common/cardThumbnailFiles';

import LinkElement from '@/views/legal/process/components/formMake/components/linkElement';
import ThreeLevelArea from '@/components/ThreeLevelArea';
import DeptSelect from './deptSelect';
import UserSelect from './userSelect';
import PostSelect from './PostSelect';
import LinkOptions from './Element/Link';
import FormulaInput from './formulaInput';
import RichEditor from './RichEditor';
import uploadIcon from '@/assets/icon-upload-blue.png';
import { format } from '@/filters/date';
import { EventBus } from '@/utils/eventBus';
import { mapState } from 'vuex';
import { mathFormula } from '@/utils/formMakeUtils';
import { initMathFormulaFunction } from '@/utils/formulaMath.js';
import { checkField } from '@/api/approvalModule';
import { decrypt } from '@/utils/secret';
import { showModal } from '@/utils/message';
import { arrRepeat, downloadWithZip } from '@/utils/tools';
import { validateEntireForm } from '@/views/approvalModule/utils/filter.js';

export default {
  components: {
    upAttachment, DeptSelect, UserSelect, PostSelect, FileShowList,
    FormulaInput, ThreeLevelArea, RichEditor, LinkElement, LinkOptions, ImgShowDialog, CardThumbnailFiles
  },
  filters: { format },
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  inject: {
    freshCheckLog: { default: null }
  },
  props: {
    value: {
      type: Object | Array | String | Number,
      default: null
    },
    element: {
      type: Object,
      default: null
    },
    isTable: {
      type: Boolean,
      default: false
    },
    isCardTable: {
      type: Boolean,
      default: false
    },
    isPreView: { // 是否配置中
      type: Boolean,
      default: false
    },
    isMiddle: {
      type: Boolean,
      default: false
    },
    isDetail: { // 是否详情页展示
      type: Boolean,
      default: false
    },
    isInDetail: { // 是否详情页展示，isDetail可能因为事件而改变，导致实际在详情页而 isDetail 为false，这个属性不会改变，详情页永远为true
      type: Boolean,
      default: false
    },
    isWeiboOrWeixin: { // 是否双微发文审核，区别是上传的接口不同
      type: Boolean,
      default: false
    },
    useInnerUpload: { // 是否使用内网上传
      type: Boolean,
      default: false
    },
    formOptions: {
      type: Object,
      default: () => ({})
    },
    subformIndex: {
      type: Number,
      default: 0
    },
    subformElement: {
      type: Object,
      default: () => ({})
    },
    eventData: { // 事件
      type: Object,
      default: null
    }
  },
  data() {
    return {
      uploadIcon,
      selectFlag: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    // 组件宽度
    widthStyle() {
      if (this.showMobilePage || this.isTable) {
        return { width: '100%' };
      }
      return { width: this.element.options && this.element.options.width ? this.element.options.width + 'px' : '240px' };
    },
    computedValue: {
      get() {
        if ((this.isTable || this.isCardTable) && !this.isPreView) {
          return this.value;
        }
        return this.element.value;
      },
      set(val) {
        if ((this.isTable || this.isCardTable) && !this.isPreView) {
          this.$emit('changeValue', val);
        } else {
          this.$set(this.element, 'value', val);
          if (this.element.type === 'date' && !val) {
            this.$set(this.element, 'value', '');
          }
        }
      }
    },
    normalType() {
      const element = this.element;
      const computedValue = this.computedValue;
      if (!computedValue && computedValue !== 0 && computedValue !== false) return false;
      if (['input', 'radio', 'formulaInput'].includes(element.type)) {
        if ((computedValue || computedValue === 0) &&
            ((element.type === 'input' && element.options.dataType === 'number') || (element.type === 'formulaInput' && !element.options.modeType)) &&
            (element.options.precision || element.options.precision === 0)) {
          if (element.options.isShowPercentage) {
            return computedValue + '%';
          }
          return Number(Number(computedValue).toFixed(element.options.precision));
        }
        if (computedValue === false) return 'false';
        return computedValue;
      } else if (element.type === 'select') {
        if (element.options.multiple) {
          return computedValue.map(i => i).join(',');
        } else {
          return computedValue;
        }
      } else if (element.type === 'checkbox') {
        return computedValue.map(i => i).join(',');
      } else if (element.type === 'department') {
        if (element.options.multiple) {
          return computedValue.map(i => i.name).join(',');
        } else {
          return computedValue.name;
        }
      } else if (element.type === 'post') {
        if (Array.isArray(computedValue)) {
          return computedValue.map(i => i.name).join(',');
        } else {
          return computedValue.name;
        }
      } else if (element.type === 'address') {
        return this.setAddress(computedValue);
      }
      return false;
    }
  },
  created() {
    if (this.isPreView) {
      EventBus.$on('selectMultipleChange', () => {
        this.selectFlag = true;
        this.$nextTick(() => {
          this.selectFlag = false;
        });
      });
    }
  },
  mounted() {
    if (this.element && this.element.type === 'textarea') {
      this.$nextTick(() => {
        this.$refs[`input_${this.element.key}`] && this.$refs[`input_${this.element.key}`].resizeTextarea();
      });
    }
  },
  methods: {
    hasContentCache(element) {
      if (!['textarea', 'input'].includes(element.type)) return false;
      return !!element.options.contentCache && Array.isArray(element.options.options) && element.options.options.length;
    },
    getType(element) {
      const format = element.options.format;
      const isRange = element.options.isRange;
      if (format === 'yyyy/MM') {
        return `month${isRange ? 'range' : ''}`;
      } else if (format === 'yyyy/MM/dd HH:mm:ss') {
        return `datetime${isRange ? 'range' : ''}`;
      }
      return `date${isRange ? 'range' : ''}`;
    },
    // 附件
    complateSetData(item, { data, fileName, processName }) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (!this.computedValue) {
        this.computedValue = [fileList];
      } else {
        const previewIndex = this.computedValue.findIndex(i => {
          return i.name === processName && i.type === 'preview';
        });
        if (previewIndex >= 0) {
          this.computedValue.splice(previewIndex, 1, fileList);
        } else {
          this.computedValue.push(fileList);
        }
      }
      this.clearValidate(this.element.key);

      this.handelChangeValue();
      // item.value.push(fileList);
    },
    removeFileList(item, { file, index }) {
      this.computedValue.splice(index, 1);
      this.handelChangeValue();
    },
    threeLevelArea(data) {
      if ((this.isTable || this.isCardTable) && !this.isPreView) {
        this.$emit('changeValue', data);
      } else {
        this.element.value = data;
      }
      this.handelChangeValue();
    },
    getFormat(format) {
      if (!format) return 'YYYY/MM/DD HH:mm:ss';
      format = format.replace('yyyy', 'YYYY');
      format = format.replace('dd', 'DD');
      return format;
    },
    getUserName(data) {
      if (typeof data !== 'object' && data) return data;
      if (typeof data === 'object' && data.userName) return data;
      if (!this.isInDetail && this.userInfo) {
        return this.userInfo;
      }
      return '';
    },
    // 获取详情地址
    setAddress(list) {
      if (Array.isArray(list) && list.length) {
        return list.join('-');
      }
      return '';
    },
    clearValidate(key) {
      this.$emit('clearValidate', key);
    },
    numberInputChange(element) {
      if (element.type === 'input' && element.options.dataType === 'number') {
        let minVal = -99999999999;
        let maxVal = 99999999999;
        if (element.options.numberRange) {
          minVal = element.options.numberRange[0] || element.options.numberRange[0] === 0 ? element.options.numberRange[0] : -99999999999;
          maxVal = element.options.numberRange[1] || element.options.numberRange[1] === 0 ? element.options.numberRange[1] : 99999999999;
        }
        if (this.computedValue || this.computedValue === 0) {
          let val = this.computedValue;
          const value = element.options.isShowPercentage ? Number(this.computedValue) / 100 : Number(this.computedValue);
          if (value < minVal) val = element.options.isShowPercentage ? minVal * 100 : minVal;
          if (value > maxVal) val = element.options.isShowPercentage ? maxVal * 100 : maxVal;
          const precision = element.options.precision;
          if (precision || precision === 0) {
            val = Number(Number(val).toFixed(precision));
          }
          this.computedValue = element.options.defaultType ? val.toString() : val;
        }
      }
      this.$emit('subformInputChange', {
        fieldKey: element.key,
        fieldValue: this.computedValue
      });
      this.handelChangeValue();
    },
    suggestionsSearch(queryString, cb) {
      const element = this.element;
      if (element.options && element.options.options) {
        cb(element.options.options);
      }
    },
    handleAutocompleteSelect(data) {
      this.$nextTick(() => {
        const element = this.element;
        if (element.type === 'input' && element.options.dataType === 'number') {
          this.numberInputChange(element);
        }
      });
      this.handelChangeValue();
    },
    // 所有字段的value 都会经过这里，这里进行公式的处理计算
    handelChangeValue() {
      const element = this.element;
      const isTable = this.isTable || this.isCardTable;
      if (!this.isPreView) {
        this.$nextTick(() => {
          mathFormula(this.formOptions, element, isTable);
          this.$emit('changeValueData', element);

          // 表单提交校验
          validateEntireForm(this.formOptions);
        });
      }
      setTimeout(() => {
        this.$nextTick(() => {
          initMathFormulaFunction(this.formOptions, element);
        });
      }, 10);
    },
    handleFormUserSelect(data) {
      this.$emit('handleFormUserSelect', data);
    },
    clearInputValue(element) {
      this.computedValue = '';
      this.$nextTick(() => {
        this.numberInputChange(element);
      });
    },
    getFocus() {
      const value = {
        fieldKey: this.element.key,
        fieldValue: this.computedValue
      };
      this.$emit('getFocus', value);
    },
    changeInput(val, e) {
      this.$emit('subformInputChange', {
        fieldKey: e.key,
        fieldValue: val
      });
      // this.$emit('changeInput', val);
    },
    getStyle(element) {
      const noWidth = ['switch', 'radio', 'checkbox', 'upAttachment', 'createUser', 'createTime', 'workflowId', 'richEditor'];
      if (noWidth.includes(element.type)) return '';
      if (this.showMobilePage) return { width: '' };
      let width = element.options && element.options.width ? element.options.width + 'px' : '240px';
      if (this.isDetail) { width = ''; }
      if (this.isTable) return { width: '100%' };
      return {
        width
      };
    },
    trimString(str) {
      if (!str) return '--';
      str = str.replace(/^\s+|\s+$/g, '');
      return str;
    },
    // 加密字段
    showSecretModel() {
      showModal('请确认是否查看?<br />查看后将记录您的行为到日志', '', { dangerouslyUseHTMLString: true }).then(_ => {
        this.showSecretVal(true);
      });
    },
    showSecretVal(isHttp) {
      // 解密
      const element = this.element;
      const isTable = this.isTable || this.isCardTable;
      if (isTable && element.type !== 'upAttachment') {
        // 子表单字段解密
        if (this.subformElement && this.subformElement.value) {
          this.subformElement.value.forEach(i => {
            i[element.key] = decrypt(i[element.key], element);
          });
        }
      } else if (element.type !== 'upAttachment') {
        this.computedValue = decrypt(this.computedValue, element);
      }
      this.$set(this.element, '_isShowSecret', true);
      this.$forceUpdate();
      const detailId = this.$route.query.id;
      const processId = this.$route.query.processId;
      if (isHttp && processId && detailId) {
        let fieldName = this.element.name;
        if (isTable && this.subformElement) {
          fieldName = `${this.subformElement.name}.${fieldName}`;
        }
        const params = {
          fieldName,
          processId,
          id: detailId
        };
        checkField(params).then(() => {
          if (this.freshCheckLog) this.freshCheckLog();
        });
      }
    },
    userChange(val) {
      this.forEachList(this.formOptions.list, val);
    },
    forEachList(list, val, subformValue) {
      // 栅格布局下的表单需要另做处理
      for (let i = 0; i < list.length; i++) {
        if (list[i].type === 'department') {
          const key = list[i].options.defaultValue;
          let subformKey = '';
          if (subformValue) {
            subformKey = list[i].key;
          }
          if (key === val.key && !list[i].options.multiple) {
            // 部门单选
            if (val.val && val.val.length) {
              // 人员多选，只取第一个人员的第一个一级部门
              const temp = val.val[0];
              if (temp.deptName.length) {
                this.setDeptData(subformValue, subformKey, temp.deptName[0], list, i);
              }
            } else if (val.val && Object.prototype.toString.call(val.val) === '[object Object]') {
              // 人员单选
              if (val.val.deptName.length) {
                this.setDeptData(subformValue, subformKey, val.val.deptName[0], list, i);
              }
            } else {
              // 还要考虑清除时
              this.setDeptData(subformValue, subformKey, null, list, i);
            }
          } else if (key === val.key && list[i].options.multiple) {
            // 部门多选
            if (val.val && val.val.length) {
              // 人员多选，取全部人员的全部一级部门
              let temp = [];
              val.val.forEach(item => {
                if (item.deptName) {
                  temp = temp.concat(item.deptName);
                }
              });
              // 还需要去重，不同人员的一级部门可能相同
              temp = arrRepeat(temp);
              this.setDeptData(subformValue, subformKey, temp, list, i);
            } else if (val.val && Object.prototype.toString.call(val.val) === '[object Object]') {
              // 人员单选，取人员的全部一级部门
              if (val.val.deptName.length) {
                this.setDeptData(subformValue, subformKey, val.val.deptName, list, i);
              }
            } else {
              this.setDeptData(subformValue, subformKey, null, list, i);
            }
          }
        } else if (list[i].type === 'grid' && list[i].columns) {
          for (let j = 0; j < list[i].columns.length; j++) {
            if (list[i].columns[j].list) {
              this.forEachList(list[i].columns[j].list, val);
            }
          }
        } else if (list[i].type === 'subform' && list[i].subform) {
          this.forEachList(list[i].subform, val, list[i].value);
        }
      }
    },
    setDeptData(subformValue, subformKey, value, list, i) {
      // 赋值时需要考虑是否是子表单里的部门，子表单需要遍历给每行的部门都赋值，清除时也要
      if (subformValue) {
        subformValue.forEach(cur => {
          cur[subformKey] = value;
        });
      } else {
        list[i].value = value;
      }
    },
    async allDownload(list, element) {
      let filename;
      if (this.subformElement && this.subformIndex) {
        // 特殊需求，需要拿到同一行的作品名称字段，当做zip名称
        const el = this.subformElement.subform.find(i => i.name === '作品名称');
        if (el) {
          filename = this.subformElement.value[this.subformIndex][el.key];
        }
      }
      try {
        element._downloadLoading = true;
        await downloadWithZip(list, filename);
      } finally {
        element._downloadLoading = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.element-item {
  display: flex;
  min-height: 32px;
  align-items: center;
  &::v-deep {
    .el-select__tags-text {
      overflow: hidden !important;
      text-overflow: ellipsis !important;
      max-width: 100% !important;
      display: inline-block !important;
    }
    .el-tag__close{
      flex-shrink: 0;
      top: 1px;
    }
    .el-tag--info {
      color: #406EFF;
      background-color: #ecf1ff;
      max-width: 100%;
      display: flex;
      align-items: center;
    }
    .el-radio,.el-checkbox {
      line-height: 32px;
    }
  }
}
.normal-element-item {
  .defaultWidth {
    width: 100%;
    max-width: 100%;
    &::v-deep {
      .el-input__inner {
        max-width: 100%;
        width: 100%;
      }
    }
  }
}
.flexStart {
  align-items: flex-start;
}
.mobile-element-item {
  flex: 1;
  .defaultWidth {
    max-width: 100%;
    width: 100%;
  }
  .dynamic-width {
    &::v-deep {
      .width240 {
        width: auto !important;
        max-width: 100% !important;
      }
    }
  }
}
.upAttachment-width {
  max-width: 100%;
}
.font-14 {
  font-size: 14px;
}
.ml5 {
  margin-left: 5px;
}
.attachment-container {
  min-width: 196px;
  max-width: 240px;
  width: 100%;
  &::v-deep {
    .el-upload-dragger {
      width: 100% !important;
    }
  }

}
.multiple-attachment-container {
  background-color: #fff;
  width: 100%;
  .upload-btn {
    display: flex;
    align-items: center;
    .content {
      color: #dddddd;
    }
    .content-link {
      color: #406EFF;
    }
    img {
      width: 16px;
      margin-left: 4px;
    }
  }
  &::v-deep {
    .fb-upload-container, .file-container, .fb-up-attachment {
      width: auto;
      max-width: 100%;
      width: 100% !important;
    }
    .file-container {
      max-height: 50px;
      overflow-y: auto;
    }
  }
}
.secret-item {
  display: flex;
  align-items: center;
  .secret-val {
    margin-right: 5px;
  }
}
.pdr {
  padding-right: 10px;
}
.ellipsisOne-group {
  display: flex;
  flex-wrap: wrap;
  max-width: 100%;
  &::v-deep {
    .el-checkbox,.el-radio {
      height: 32px;
      display: flex;
      align-items: center;
      max-width: 100%;
    }
    .el-checkbox__label,.el-radio__label {
      max-width: 100%;
    }
  }
}
.tip-container {
  align-self: flex-start;
  display: flex;
  line-height: 32px;
  height: 32px;
  align-items: center;
}
.input-percentage {
  &::v-deep {
    .el-input {
      position: relative;
    }
    .el-input__inner {
      padding-right: 25px;
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }
    .el-input-group__append {
      padding: 0;
      background-color: transparent;
      border: none;
      border-radius: 0;
    }
  }
}
.donwload-container {
  .all-download {
    margin-top: 10px
  }
}
.clear-autocomplete {
  cursor: pointer;
  font-size: 14px;
  color: #ddd;
  margin-left: 5px;
}
.autocomplete-append {
  display: flex;
  align-items: center;
  height: 100%;
  position: absolute;
  right: 5px;
  top: 0;
}
.textarea-content {
  white-space: pre-line;
  line-height: 1.3;
  padding-top: 6px;
  word-break: break-all;
}

.input-percentage-append {
  font-size: 14px;
  color: #333;
}
.auto-input {
  &::v-deep {
    .el-input-group__append {
      background-color: transparent;
      border-color: transparent;
    }
  }
}
</style>
<style lang="scss">
.el-select-dropdown__item{
  max-width: 100% !important;
}
.richeditor-readonly {
  width: 100%;
  div, span, applet, object, iframe,
  h1, h2, h3, h4, h5, h6, p, blockquote, pre,
  a, abbr, acronym, address, big, cite, code,
  del, dfn, em, img, ins, kbd, q, s, samp,
  small, strike, strong, sub, sup, tt, var,
  b, u, i, center,
  dl, dt, dd, ol, ul, li,
  fieldset, label, legend,
  table, caption, tbody, tfoot, thead, tr, th, td,
  article, aside, canvas, details, embed,
  figure, figcaption, footer, header, hgroup,
  menu, nav, output, ruby, section, summary,
  time, mark, audio, video {
    margin: 0! important;
    padding: 0! important;
    max-width: 100%;
  }
  .tb-table {
    border-collapse: collapse;
    border-spacing: 0;
    td, th {
      border: 1px solid #aaa;
    }
  }
}
</style>
